<template>
  <div class="chat_box">
    <el-scrollbar ref="scrollDiv" @scroll="handleScrollTop">
      <div class="ai-chat__content p-24">
        <!-- 开场白组件 -->
        <div class="opening-remarks mb-16">
          <div class="opening-remarks-info">
            <img class="logo" :src="defImg" alt="" />
            <div>
              <div class="title">{{ agentInfo?.name }}</div>
              <div class="description">{{ agentInfo?.description }}</div>
            </div>
          </div>
          <div class="opening-remarks-items" v-if="tipTag && tipTag.length" style="background-color: #f0f5ff">
            <div
              :class="{ tip: true, 'tag-item': tipTag.length === 0 }"
              style="white-space: pre-line"
            >
              您好，智能助理【{{ tip }}】将与您对话，试着问：
            </div>
            <div class="tag">
              <div class="tag-item" v-for="(v, i) in tipTag" :key="v + i" @click="debounceSendMessage(v)">
                {{ v }}
              </div>
            </div>
          </div>
        </div>
        <template v-for="(item) in chatList" :key="item.questionId">
          <!-- 问题 -->
          <QuestionContent :chat-record="item" />
          <!-- 回答 -->
          <AnswerContent :chat-record="item" />
        </template>
      </div>
    </el-scrollbar>

    <ChatInputOperate ref="refChatInput" />
  </div>
</template>

<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
import QuestionContent from './QuestionContent.vue'
import AnswerContent from './AnswerContent.vue'
import ChatInputOperate from './ChatInputOperate.vue'
import defImg from '@/assets/agent/def_agent.svg'
import useStore from '@/stores'
import bus from '@/bus'
import { debounce } from 'lodash-es'

const refChatInput = ref()
const { chatbi } = useStore()
const scrollDiv = ref()
const chatList = computed(() => chatbi.chatList)
const agentInfo: any = computed(() => chatbi.activeAgent)
const tipTag = computed(() => {
  // @ts-ignore
  const examples = chatbi.activeAgent?.examples
  return Array.isArray(examples) ? examples : []
})
const tip = computed(() => {
  // @ts-ignore
  const name = chatbi.activeAgent?.name
  return name || ''
})

const scrollAuto = ref(false); // 默认不是自动滚动
const lastScrollTop = ref(0); // 记录上一次滚动位置

function handleScrollTop($event: any) {
  const currentScrollTop = $event.scrollTop;
  // 判断滚动方向（true=向上滚动，false=向下滚动）
  const isScrollUp = currentScrollTop < lastScrollTop.value;
  // 更新上一次滚动位置
  lastScrollTop.value = currentScrollTop;

  if (isScrollUp) {
    // console.log('用户正在向上滚动');
    scrollAuto.value = false;
  } else {
    // console.log('用户正在向下滚动');
  }
  // console.log('[ scrollToTop... ]')
  const h = (document.querySelector('.el-scrollbar__view') as HTMLElement)?.offsetHeight ? (document.querySelector('.el-scrollbar__view') as HTMLElement)!.offsetHeight / 2 : 500;
  if ( $event.scrollTop < h){ 
    bus.emit('scrollToTop')
  }
}

function scrollToBottom() {
  if (!scrollAuto.value) {
    return;
  }

  // console.log('[ scrollToBottom... ]')
  const scrollbar = scrollDiv.value;
  if (scrollbar && scrollbar.$el) {
    const scrollWrapper = scrollbar.$el.querySelector('.el-scrollbar__wrap');
    if (scrollWrapper) {
      scrollWrapper.scrollTop = scrollWrapper.scrollHeight;
    }
  }
}

function setsSrollToAuto(msg: boolean) {
  scrollAuto.value = msg || true
}

const debounceSendMessage = debounce(sendMessage, 300)

function sendMessage(item: any) {
  refChatInput.value.sendChatHandle(item)
}

onMounted(()=> {
  bus.on('scrollToBottom', scrollToBottom)
  bus.on('scrollToAuto', setsSrollToAuto)
})

onBeforeUnmount (()=> {
  bus.off('scrollToBottom', scrollToBottom)
  bus.off('scrollToAuto', setsSrollToAuto)
})


</script>

<style lang="scss" scoped>
.chat_box {
  height: calc(100% - 80px);
}
.opening-remarks-info {
  display: flex;
  background: linear-gradient(90deg, #e7eeff 0%, #daeaff 48%, #daf4ff 100%);
  padding: 16px;
  align-items: center;
  border-radius: 12px 12px 0 0;
  .logo {
    width: 60px;
    height: 60px;
    margin-right: 16px;
  }
  .title {
    font-weight: 500;
    font-size: 16px;
    color: #191919;
    line-height: 19px;
  }
  .description {
    font-weight: 400;
    font-size: 12px;
    color: #333;
    line-height: 18px;
  }
}

.opening-remarks-items {
  background: #fff;
  border-radius: 0 0 12px 12px;
  padding: 16px;
  .tip {
    font-weight: 400;
    font-size: 14px;
    color: #191919;
    line-height: 17px;
    margin-bottom: 10px;
  }
  .tag {
    display: flex;
    flex-wrap: wrap;
    .tag-item {
      padding: 5px 20px;
      font-size: 12px;
      color: #6489e3;
      background: #f0f5ff;
      border-radius: 4px;
      margin-right: 10px;
      cursor: pointer;
    }
  }
}
</style>
